package com.badibadi.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import com.badibadi.activity.ChatActivity.Chat_List_Adapter;
import com.badibadi.infos.ClueTypeModel;
import com.badibadi.infos.Results;
import com.badibadi.infos.TypeId;
import com.badibadi.infos.infoUserModle;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MySharePreferences;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.mytools.ViewHolder;
import com.badibadi.uniclubber.R;
import com.badibadi.uniclubber.R.layout;
import com.badibadi.uniclubber.R.menu;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

//activity_chat_setting_see_historical_data
public class ChatSettingActivity extends BaseActivity implements
		OnClickListener {

	private Button return_btn, activity_chat_setting_delete;
	private ImageView activity_chat_setting_head, message_lock;
	private TextView activity_chat_setting_name;
	private TextView activity_chat_setting_qianming;
	private LinearLayout fenzu_linear, linear_fensuo;
	private infoUserModle infoUserModle;
	private List<TypeId> ids;
	private DisplayImageOptions options;
	private AlbumAdapter_new adapter_new;
	private Spinner activity_chat_setting_fenzhu;
	private LinearLayout activity_chat_setting_see_historical_data;
	private String w_b = "";
	private boolean judw_b = false;
	private String fid;
	private Results results, results2, results3, results4, results5;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				try {
					Utils.ExitPrgress(ChatSettingActivity.this);
					Utils.showMessage(ChatSettingActivity.this, getResources()
							.getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 2:
				try {
					Utils.ExitPrgress(ChatSettingActivity.this);
					ImageLoader.getInstance().displayImage(
							Constants.BadiDownImgUrl + infoUserModle.getHead()
									+ Constants.appPhoto4img,
							activity_chat_setting_head, options);
					activity_chat_setting_name.setText(infoUserModle
							.getNickName());
					activity_chat_setting_qianming.setText(infoUserModle
							.getMotto());

					if (!infoUserModle.getTypeid().equals(
							infoUserModle.getBlacklist())) {
						message_lock.setSelected(true);
						w_b = "白";
						fenzu_linear.setVisibility(View.VISIBLE);
						linear_fensuo
								.setBackgroundResource(R.drawable.layer_list_selector_layer_top);
//						   
					} else {
						w_b = "黑";
						message_lock.setSelected(false);
						fenzu_linear.setVisibility(View.GONE);
						linear_fensuo
								.setBackgroundResource(R.drawable.shape_layout_bg_can_click);
//						   
					}
					friendGroup();
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 3:
				Utils.ExitPrgress(ChatSettingActivity.this);
				Utils.showMessage(ChatSettingActivity.this, getResources()
						.getString(R.string.l_xa10));
				break;
			case 4:
				Utils.ExitPrgress(ChatSettingActivity.this);
				adapter_new = new AlbumAdapter_new(ChatSettingActivity.this);
				activity_chat_setting_fenzhu.setAdapter(adapter_new);
				if (ids.size() > 0) {
					for (int i = 0; i < ids.size(); i++) {
						if (ids.get(i).getId()
								.equals(infoUserModle.getTypeid())) {
							activity_chat_setting_fenzhu.setSelection(i);
						}
					}
				}
				break;
			case 5:
				Utils.ExitPrgress(ChatSettingActivity.this);
				Utils.showMessage(ChatSettingActivity.this,
						results3.getRetmsg());
				if (w_b.equals("黑")) {
					message_lock.setSelected(false);
					fenzu_linear.setVisibility(View.GONE);
					linear_fensuo
							.setBackgroundResource(R.drawable.shape_layout_bg_can_click);
				} else if (w_b.equals("白")) {
					message_lock.setSelected(true);
					fenzu_linear.setVisibility(View.VISIBLE);
					linear_fensuo
							.setBackgroundResource(R.drawable.layer_list_selector_layer_top);
					// friendGroup();
				}
				infoUser_Blacklist();
				break;
			case 6:
				Utils.ExitPrgress(ChatSettingActivity.this);
				Utils.showMessage(ChatSettingActivity.this,
						results4.getRetmsg());
				if (Constants.Close_Chat_handler != null) {
					Constants.Close_Chat_handler.sendEmptyMessage(4);
				}
				finish();
				break;
			case 7:
				Utils.ExitPrgress(ChatSettingActivity.this);
				MySharePreferences preferences = new MySharePreferences(
						ChatSettingActivity.this, "user");
				preferences.put("black_list_id", results5.getRetmsg());
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.activity_chat_setting);
		try {
			fid = getIntent().getStringExtra("fid");
		} catch (Exception e) {
			// TODO: handle exception
		}
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.noimage)
				.showImageOnFail(R.drawable.noimage).cacheInMemory()
				.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5)).build();
		ids = new ArrayList<TypeId>();
		activity_chat_setting_fenzhu = (Spinner) this
				.findViewById(R.id.activity_chat_setting_fenzhu);
		activity_chat_setting_delete = (Button) this
				.findViewById(R.id.activity_chat_setting_delete);
		message_lock = (ImageView) this.findViewById(R.id.message_lock);
		fenzu_linear = (LinearLayout) this.findViewById(R.id.fenzu_linear);
		linear_fensuo = (LinearLayout) this.findViewById(R.id.linear_fensuo);
		message_lock.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (!message_lock.isSelected()) {
					if (ids != null && ids.size() > 0) {
						moveFriend(ids.get(0).getId());
					}
					w_b = "白";
					// message_lock.setSelected(false);
				} else {
					moveFriend(infoUserModle.getBlacklist());
					w_b = "黑";
					// message_lock.setSelected(true);
				}
			}
		});
		activity_chat_setting_delete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				deleteFriend();
			}
		});
		activity_chat_setting_fenzhu
				.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						if (ids != null && !ids.isEmpty()) {
							// w_b = "白";
							moveFriend(ids.get(arg2).getId());
						} else {
//							   
						}
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub

					}
				});
		return_btn = (Button) this.findViewById(R.id.return_btn);
		return_btn.setOnClickListener(this);
		activity_chat_setting_head = (ImageView) this
				.findViewById(R.id.activity_chat_setting_head);
		activity_chat_setting_name = (TextView) this
				.findViewById(R.id.activity_chat_setting_name);
		activity_chat_setting_qianming = (TextView) this
				.findViewById(R.id.activity_chat_setting_qianming);
		activity_chat_setting_see_historical_data = (LinearLayout) this
				.findViewById(R.id.activity_chat_setting_see_historical_data);
		activity_chat_setting_see_historical_data.setOnClickListener(this);
		infoUser();
	}

	private void infoUser() {
		Utils.showPrgress(ChatSettingActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", Utils.getUid(ChatSettingActivity.this));
				map.put("fid", fid);
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "chat/infoUser");
				if (content != null) {
					results = Utils.checkResult_NNN(getApplicationContext(),
							content);
					//    ("设置界面返回参数是:" + content);
//					   
					if (results != null && !results.getRetmsg().equals("null")
							&& results.isRet()) {
						try {
							infoUserModle = JSONUtils.getEntityByJsonString(
									results.getRetmsg(), infoUserModle.class);
							handler.sendEmptyMessage(2);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	private void infoUser_Blacklist() {
		// Utils.showPrgress(ChatSettingActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", Utils.getUid(ChatSettingActivity.this));
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "chat/blacklist");
				if (content != null) {
					results5 = Utils.checkResult_NNN(getApplicationContext(),
							content);
					//    ("设置界面返回参数是:" + content);
//					   
					if (results5 != null
							&& !results5.getRetmsg().equals("null")
							&& results5.isRet()) {
						handler.sendEmptyMessage(7);
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	private void deleteFriend() {
		Utils.showPrgress(ChatSettingActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", Utils.getUid(ChatSettingActivity.this));
				map.put("deleteId", fid);
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "chat/deleteFriend");
//				   
				if (content != null) {
					results4 = Utils.checkResult_NNN(getApplicationContext(),
							content);
					//    ("设置界面返回参数是:" + content);
//					   
					if (results4 != null
							&& !results4.getRetmsg().equals("null")
							&& results4.isRet()) {
						handler.sendEmptyMessage(6);
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	private void friendGroup() {
		Utils.showPrgress(ChatSettingActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				ids.clear();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", Utils.getUid(ChatSettingActivity.this));
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "chat/friendGroup");
				if (content != null) {
					results2 = Utils.checkResult_NNN(getApplicationContext(),
							content);
//					   ("好友分组返回参数是:" + content);
					if (results2 != null
							&& !results2.getRetmsg().equals("null")
							&& results2.isRet()) {
						try {
							ids = JSONUtils.getListByJsonString(
									results2.getRetmsg(), TypeId.class);
							handler.sendEmptyMessage(4);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	private void moveFriend(final String groupid) {
		Utils.showPrgress(ChatSettingActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", Utils.getUid(ChatSettingActivity.this));
				map.put("fid", fid);
				map.put("groupId", groupid);
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "chat/moveFriend");
				if (content != null) {
					results3 = Utils.checkResult_NNN(getApplicationContext(),
							content);
					//    ("好友分组返回参数是:" + content);
					if (results3 != null
							&& !results3.getRetmsg().equals("null")
							&& results3.isRet()) {
						handler.sendEmptyMessage(5);
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	public void OnClick(View v) {
		if (v.isSelected() == true)
			v.setSelected(false);
		else
			v.setSelected(true);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.return_btn:
			ChatSettingActivity.this.finish();
			break;
		case R.id.activity_chat_setting_see_historical_data:
			Intent intent = new Intent(ChatSettingActivity.this,
					Chat_history_Activity.class);
			intent.putExtra("fid", fid);
			startActivity(intent);
			break;
		}
	}

	private class AlbumAdapter_new extends BaseAdapter {
		private Context context;

		public AlbumAdapter_new(Context context) {
			this.context = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return ids.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return ids.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View convertView, ViewGroup arg2) {
			if (convertView == null) {
				convertView = ViewHolder.buildView(context,
						R.layout.spinner_item_main, arg2);
			}
			ViewHolder viewHolder = (ViewHolder) convertView.getTag();
			TextView name = viewHolder.getViewById(R.id.spinner_item_name);
//			   ("名字是:" + ids.get(arg0).getName());
			name.setText(ids.get(arg0).getType());
			name.setTextColor(getResources().getColor(R.color.black));
			return convertView;
		}
	}

}
